#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from smtplib import SMTP, SMTPException
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def main():
    sender = 'admin@qq.com'
    receivers = ['test@sina.com']
    # 创建一个带有附件的邮件消息对象
    message = MIMEMultipart()

    # 创建文本内容
    text_content = MIMEText('用Python发送邮件的示例代码', 'plain', 'utf-8')
    # 收件人
    message['From'] = Header('admin', 'utf-8')
    # 发件人
    message['To'] = Header('test', 'utf-8')
    # 邮件主题
    message['Subject'] = Header('示范代码邮件', 'utf-8')
    # 将文本内容添加到邮件消息对象中
    message.attach(text_content)

    # 读取本地一张图片作为附件添加到邮件消息对象中
    with open('./images.jpeg', 'rb', ) as f:
        jpg = MIMEText(f.read(), 'base64', 'utf-8')
        jpg['Content-Type'] = 'content-type: image/jpeg'
        jpg['Content-Disposition'] = 'attachment; filename=images.jpeg'
        message.attach(jpg)

    try:
        # 邮件服务器
        smtper = SMTP('smtp.exmail.qq.com')
        # 邮件服务器授权登录密码
        smtper.login(sender, '授权码')
        # 发送邮件
        smtper.sendmail(sender, receivers, message.as_string())
        # 与邮件服务器断开连接
        smtper.quit()
        print('发送完成!')
    except SMTPException:
        print("Error: 无法发送邮件")


if __name__ == '__main__':
    main()
